package com.example.common.mvvm.viewmodel;


import android.util.Log;

import androidx.lifecycle.ViewModel;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.common.entity.NetErrorEntity;
import com.example.common.fieid.DataActionEntity;
import com.example.common.mvvm.databus.LiveDataBus;
import com.example.common.mvvm.model.BaseRespository;
import com.example.common.entity.BaseEntity;

import java.lang.reflect.ParameterizedType;

import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class BaseViewModel<M extends BaseRespository> extends ViewModel implements IViewModel, Observer<BaseEntity> {

    private CompositeDisposable compositeDisposable;
    protected M respository;//负责全部网络请求

    public BaseViewModel(){
        compositeDisposable=new CompositeDisposable();
        initRespository();
    }

    private void initRespository(){
        ParameterizedType type= (ParameterizedType) getClass().getGenericSuperclass();
        Class clazz= (Class) type.getActualTypeArguments()[0];
        try {
            respository= (M) clazz.newInstance();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    public  abstract void onResult(BaseEntity entity);

    protected abstract  void initData();

    @Override
    public void onCreate() {
        initData();
    }

    @Override
    public void onDestroy() {
        //统一解除Rxjava订阅
         compositeDisposable.dispose();
         compositeDisposable.clear();
    }

    //显示Dialog
    protected void showDialog(){

    }
    //关闭Dialog
    protected void hideDialog(){

    }


    @Override
    public void onSubscribe(Disposable d) {
        //统一保存订阅记录
        compositeDisposable.add(d);
        showDialog();
    }

    @Override
    public void onNext(BaseEntity baseEntity) {
        //根据返回值BaseEntity  进行类型判断->是否为具体出错类型
        if (baseEntity instanceof NetErrorEntity){
            NetErrorEntity netErrorEntity= (NetErrorEntity) baseEntity;
            ToastUtils.showShort(netErrorEntity.message);
            return;
        }
        Log.e("asd", "onNext: "+"asd");
        onResult(baseEntity);
    }

    @Override
    public void onError(Throwable e) {
        LogUtils.e("onError"+e.getMessage());
        ToastUtils.showShort("请求错误");
    }

    @Override
    public void onComplete() {
        hideDialog();
    }

    public static class UIDataFunction{
        private LiveDataBus<DataActionEntity> uiData=new LiveDataBus<>();

        public LiveDataBus<DataActionEntity>getUiData(){
            return uiData;
        }
        public void post(DataActionEntity entity){
            uiData.setValue(entity);
        }
    }
}
